<template>
  <n-card class="talk-card" :class="{ 'talk-card-top': talk.isTop === 1 }">
    <!-- 用户信息头部 -->
    <div class="talk-header">
      <div class="user-info">
        <n-avatar
          :src="talk.avatar"
          :fallback-src="'/default-avatar.png'"
          size="medium"
          round
        />
        <div class="user-details">
          <div class="user-meta">
            <span class="nickname">{{ talk.nickname }}</span>
            <span class="time" @click="toggleTimeFormat(talk)" :title="getFullTime(talk.createTime)">
              {{ getDisplayTime(talk) }}
            </span>
          </div>
        </div>
      </div>
      <div class="talk-actions">
        <!-- 置顶图标 -->
        <div v-if="talk.isTop === 1" class="top-icon">
          <svg t="1754489803992" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="15464" width="64" height="64"><path d="M951.296 424.96L1024 352.256 671.744 0 599.04 72.704l70.144 70.656-168.96 168.96a296.96 296.96 0 0 0-286.72 75.264L143.36 458.24 72.704 387.584 0 460.8l245.248 245.248-139.776 139.776 72.704 72.704 140.288-140.288L563.2 1024l72.704-72.704-70.144-70.656 70.144-70.144a296.96 296.96 0 0 0 75.776-287.232l168.96-168.96z" fill="#66df6e" p-id="15465"></path></svg>
          </div>

        <!-- 操作下拉菜单 -->
        <n-dropdown
          placement="bottom-end"
          trigger="click"
          size="small"
          :options="getTalkOptions(talk)"
          @select="(key) => handleTalkAction(key, talk)"
        >
          <n-button quaternary circle size="small">
            <template #icon>
              <n-icon><EllipsisHorizontalIcon /></n-icon>
            </template>
          </n-button>
        </n-dropdown>
      </div>
    </div>

    <!-- 说说内容 -->
    <div class="talk-content">
      <div v-if="talk.content" class="talk-text">
        {{ talk.content }}
      </div>

      <!-- 媒体网格 -->
      <div v-if="talk.photos && talk.photos.length > 0" class="talk-media">
        <!-- 图片组预览 -->
        <n-image-group>
          <div
            class="media-grid"
            :class="getMediaGridClass(talk.photos.length)"
          >
            <div
              v-for="(photo, index) in talk.photos.slice(0, 9)"
              :key="photo.id"
              class="media-item"
            >
              <!-- 图片显示 -->
              <n-image
                v-if="isImage(photo)"
                :src="processUrl(photo.url)"
                :alt="`图片${index + 1}`"
                object-fit="cover"
                class="media-image"
                :preview-src="processUrl(photo.url)"
                lazy="true"
              />
              <!-- 视频显示 -->
              <div v-else-if="isVideo(photo)" class="video-container" @click.stop="previewVideo(photo)">
                <video
                  :src="processUrl(photo.url)"
                  class="media-video"
                  preload="metadata"
                  @ended="onVideoEnded($event)"
                />
                <div class="video-overlay">
                  <n-icon size="48" color="white">
                    <PlayIcon />
                  </n-icon>
                </div>
              </div>
              <!-- 超过9个媒体时显示遮罩 -->
              <div v-if="index === 8 && talk.photos.length > 9" class="media-overlay">
                <span class="more-count">+{{ talk.photos.length - 9 }}</span>
              </div>
            </div>
          </div>
        </n-image-group>
        <!-- 超过9个媒体时显示查看详情提示 -->
        <div v-if="talk.photos.length > 9" class="view-more">
          <n-button text size="small" @click="viewTalkDetail(talk)">
            查看全部{{ talk.photos.length }}个媒体
          </n-button>
        </div>
      </div>
      <!-- 地址、天气和操作按钮 -->
      <div class="talk-meta">
        <div class="meta-left">
          <n-text v-if="talk.address" depth="3" size="small">
            📍 {{ formatAddress(talk.address) }}
          </n-text>
          <n-text v-if="talk.weather" depth="3" size="small">
            🌤️ {{ talk.weather }}
          </n-text>
        </div>
        <div class="meta-right">
          <n-button text size="small" @click="handleLike">
            <template #icon>
              <n-icon><HeartIcon /></n-icon>
            </template>
                         {{ talk.likeCount || 0 }}
           </n-button>
           <n-button text size="small" @click="handleComment">
             <template #icon>
               <n-icon><ChatBubbleIcon /></n-icon>
             </template>
             0
           </n-button>
        </div>
      </div>
    </div>

    <!-- 底部状态标签 -->
    <div class="talk-footer">
      <n-space justify="end">
        <!-- 标签显示 -->
      <div v-if="talk.tags && talk.tags.length > 0" class="talk-tags">
        <n-tag
          v-for="tag in talk.tags"
          :key="tag"
          size="small"
          type="primary"
        >
          {{ tag }}
        </n-tag>
      </div>

      </n-space>
    </div>
  </n-card>
</template>

<script setup lang="ts">
import { computed, h, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage, useDialog } from 'naive-ui'
import dayjs from 'dayjs'
import {
  Heart as HeartIcon,
  Chatbubble as ChatBubbleIcon,
  Play as PlayIcon,
  EllipsisHorizontal as EllipsisHorizontalIcon,
  Share as ShareIcon,
  Create as EditIcon,
  Trash as TrashIcon,
  Pin as PinIcon,
  Eye as EyeIcon,
  EyeOff as EyeOffIcon
} from '@vicons/ionicons5'
import { talkApi } from '@/api/talk'
import { useUserStore } from '@/stores/user'
import type { TalkItem } from '@/types/talk'

// Props
interface Props {
  talk: TalkItem
}

const props = defineProps<Props>()

// 事件
const emit = defineEmits<{
  previewVideo: [photo: any]
  refresh: []
}>()

const router = useRouter()
const message = useMessage()
const dialog = useDialog()
const userStore = useUserStore()

// 获取当前用户ID
const currentUserId = computed(() => userStore.userInfo?.id || 0)

// 存储每个说说的时间显示状态
const timeDisplayStates = ref<Map<number, boolean>>(new Map())

// 切换时间显示格式
const toggleTimeFormat = (talk: TalkItem) => {
  const currentState = timeDisplayStates.value.get(talk.id) || false
  timeDisplayStates.value.set(talk.id, !currentState)
}

// 获取完整时间格式
const getFullTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 获取相对时间格式
const getRelativeTime = (time: string) => {
  const now = dayjs()
  const talkTime = dayjs(time)
  const diffMinutes = now.diff(talkTime, 'minute')

  if (diffMinutes < 1) {
    return '刚刚'
  } else if (diffMinutes < 60) {
    return `${diffMinutes}分钟前`
  } else if (diffMinutes < 1440) {
    return `${Math.floor(diffMinutes / 60)}小时前`
  } else if (diffMinutes < 43200) {
    return `${Math.floor(diffMinutes / 1440)}天前`
  } else {
    return talkTime.format('MM-DD HH:mm')
  }
}

// 获取显示时间（根据状态决定显示格式）
const getDisplayTime = (talk: TalkItem) => {
  const showFullTime = timeDisplayStates.value.get(talk.id) || false
  return showFullTime ? getFullTime(talk.createTime) : getRelativeTime(talk.createTime)
}

// 格式化地址 - 根据屏幕大小显示不同长度的地址
const formatAddress = (address: string) => {
  if (!address) return ''

  // 检测是否为移动端
  const isMobile = window.innerWidth <= 768

  if (isMobile) {
    // 移动端只显示最后一级地址
    const parts = address.split(',').map(part => part.trim())
    return parts[parts.length - 1] || address
  } else {
    // 桌面端显示完整地址
    return address
  }
}

// 获取媒体网格样式类
const getMediaGridClass = (count: number) => {
  if (count === 1) return 'grid-1'
  if (count === 2) return 'grid-2'
  if (count === 3) return 'grid-3'
  if (count === 4) return 'grid-4'
  if (count === 5) return 'grid-5'
  if (count === 6) return 'grid-6'
  if (count === 7) return 'grid-7'
  if (count === 8) return 'grid-8'
  return 'grid-9'
}

// 处理URL，智能处理HTTPS/HTTP
const processUrl = (url: string) => {
  if (url.startsWith('https://')) {
    return url
  }
  if (url.startsWith('http://')) {
    return url
  }
  if (url.startsWith('//')) {
    return `https:${url}`
  }
  return url
}

// 判断是否为图片
const isImage = (photo: any) => {
  const fileType = photo.fileType || ''
  return fileType.startsWith('image/') ||
         photo.url.toLowerCase().match(/\.(jpg|jpeg|png|gif|webp|bmp)$/)
}

// 判断是否为视频
const isVideo = (photo: any) => {
  const fileType = photo.fileType || ''
  return fileType.startsWith('video/') ||
         photo.url.toLowerCase().match(/\.(mp4|avi|mov|wmv|flv|webm)$/)
}

// 预览视频
const previewVideo = (photo: any) => {
  emit('previewVideo', photo)
}

// 视频播放结束
const onVideoEnded = (event: Event) => {
  const video = event.target as HTMLVideoElement
  const container = video.parentElement
  container?.classList.remove('playing')
}

// 获取说说操作选项
const getTalkOptions = (talk: TalkItem) => {
  const options = [
    {
      label: '分享',
      key: 'share',
      icon: () => h('div', { style: { fontSize: '12px' } }, [h(ShareIcon)])
    }
  ]

  // 如果是自己的说说，添加编辑、置顶、隐藏、删除选项
  if (talk.userId === currentUserId.value) {
    options.push(
      {
        label: '编辑',
        key: 'edit',
        icon: () => h('div', { style: { fontSize: '12px' } }, [h(EditIcon)])
      },
      {
        label: talk.isTop === 1 ? '取消置顶' : '置顶',
        key: 'toggleTop',
        icon: () => h('div', { style: { fontSize: '12px' } }, [h(PinIcon)])
      },
      {
        label: talk.status === 1 ? '隐藏' : '公开',
        key: 'toggleStatus',
        icon: () => h('div', { style: { fontSize: '12px' } }, [h(talk.status === 1 ? EyeOffIcon : EyeIcon)])
      },
      {
        label: '删除',
        key: 'delete',
        icon: () => h('div', { style: { fontSize: '12px' } }, [h(TrashIcon)])
      }
    )
  }

  return options
}

// 处理说说操作
const handleTalkAction = (key: string | number, talk: TalkItem) => {
  switch (key) {
    case 'share':
      handleShare(talk)
      break
    case 'edit':
      handleEdit(talk)
      break
    case 'toggleTop':
      dialog.warning({
        title: talk.isTop === 1 ? '取消置顶' : '置顶',
        content: `确定要${talk.isTop === 1 ? '取消置顶' : '置顶'}这条说说吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => handleToggleTop(talk)
      })
      break
    case 'toggleStatus':
      dialog.warning({
        title: talk.status === 1 ? '隐藏' : '公开',
        content: `确定要${talk.status === 1 ? '隐藏' : '公开'}这条说说吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => handleToggleStatus(talk)
      })
      break
    case 'delete':
      dialog.error({
        title: '删除说说',
        content: '确定要删除这条说说吗？删除后无法恢复。',
        positiveText: '删除',
        negativeText: '取消',
        onPositiveClick: () => handleDelete(talk)
      })
      break
  }
}

// 处理分享
const handleShare = (talk: TalkItem) => {
  message.success('分享功能开发中...')
}

// 处理编辑
const handleEdit = (talk: TalkItem) => {
  router.push(`/talk/edit/${talk.id}`)
}

// 处理置顶/取消置顶
const handleToggleTop = async (talk: TalkItem) => {
  const action = talk.isTop === 1 ? '取消置顶' : '置顶'
  try {
    await talkApi.updateTalk({
      id: talk.id,
      content: talk.content,
      isTop: talk.isTop === 1 ? 2 : 1,
      status: talk.status,
      address: talk.address || '',
      weather: talk.weather || '',
      photos: talk.photos || [],
      tags: talk.tags || []
    })
    message.success(`${action}成功！`)
    emit('refresh')
  } catch (error) {
    message.error(`${action}失败`)
    console.error(`${action}失败:`, error)
  }
}

// 处理隐藏/公开
const handleToggleStatus = async (talk: TalkItem) => {
  const action = talk.status === 1 ? '隐藏' : '公开'
  try {
    await talkApi.updateTalk({
      id: talk.id,
      content: talk.content,
      isTop: talk.isTop,
      status: talk.status === 1 ? 0 : 1,
      address: talk.address || '',
      weather: talk.weather || '',
      photos: talk.photos || [],
      tags: talk.tags || []
    })
    message.success(`${action}成功！`)
    emit('refresh')
  } catch (error) {
    message.error(`${action}失败`)
    console.error(`${action}失败:`, error)
  }
}

// 处理删除
const handleDelete = async (talk: TalkItem) => {
  try {
    if (!talk.id || talk.id <= 0) {
      message.error('无效的说说ID')
      return
    }

    await talkApi.deleteTalk([talk.id])
    message.success('删除成功！')
    emit('refresh')
  } catch (error) {
    message.error('删除失败')
    console.error('删除失败:', error)
  }
}

// 查看说说详情
const viewTalkDetail = (talk: TalkItem) => {
  console.log('查看详情:', talk)
}

// 点赞处理
const handleLike = () => {
  message.success('点赞功能开发中...')
  console.log('点赞')
}

// 评论处理
const handleComment = () => {
  message.success('评论功能开发中...')
  console.log('评论')
}
</script>

<style scoped>
.talk-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.talk-card-top {
  border-left: 4px solid #ff6b35;
}

.talk-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.nickname {
  font-weight: 600;
  font-size: 18px;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
  cursor: pointer;
  transition: color 0.2s ease;
}

.time:hover {
  color: #666;
}

.talk-content {
  margin-bottom: 16px;
}

.talk-text {
  font-size: 15px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 12px;
  word-wrap: break-word;
}

.talk-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;

}

.meta-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.meta-right {
  display: flex;
  gap: 8px;
}

.talk-media {
  margin-bottom: 12px;
}

.media-grid {
  display: grid;
  gap: 4px;
  border-radius: 8px;
  overflow: hidden;
  max-width: 100%;
}

.grid-1 {
  grid-template-columns: 1fr;
  max-width: 300px;
}

.grid-2 {
  grid-template-columns: 1fr 1fr;
  max-width: 400px;
}

.grid-3 {
  grid-template-columns: 1fr 1fr 1fr;
  max-width: 500px;
}

.grid-4 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  max-width: 400px;
}

.grid-5 {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  max-width: 500px;
}

.grid-6 {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  max-width: 500px;
}

.grid-7 {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  max-width: 500px;
}

.grid-8 {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  max-width: 500px;
}

.grid-9 {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  max-width: 500px;
}

.media-item {
  aspect-ratio: 1;
  cursor: pointer;
  transition: opacity 0.3s ease;
  position: relative;
  overflow: hidden;
}

.media-item:hover {
  opacity: 0.8;
}

.media-image {
  width: 100%;
  height: 100%;
  border-radius: 4px;
  object-fit: cover;
}

.video-container {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.media-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.3s ease;
}

.video-container:hover .video-overlay {
  opacity: 0.8;
}

.video-container.playing .video-overlay {
  opacity: 0;
}

.media-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.more-count {
  color: white;
  font-size: 18px;
  font-weight: bold;
}

.view-more {
  text-align: center;
  margin-top: 8px;
}

.talk-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 12px;
}

.talk-footer {
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  margin-bottom: -20px;
}

.talk-actions {
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
}

.top-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  color: #ff6b35;
  animation: pulse 2s infinite;
}

.top-icon svg {
  width: 20px;
  height: 20px;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .talk-card {
    border-radius: 8px;
  }

  .nickname {
    font-size: 15px;
  }

  .talk-text {
    font-size: 14px;
  }

  .talk-meta {
    /* 保持同一行布局 */
    flex-direction: row;
    align-items: center;
    gap: 8px;
  }

  .meta-left {
    /* 保持同一行布局 */
    flex-direction: row;
    align-items: center;
    gap: 8px;
    flex: 1;
  }

  .meta-right {
    /* 保持右对齐 */
    align-self: flex-end;
    flex-shrink: 0;
  }
}
</style>
